package com.stx.threeGrup.controller;

import com.stx.threeGrup.model.Results;
import com.stx.threeGrup.model.automodel.Picture;
import com.stx.threeGrup.service.PictureService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.List;

@Controller
@RequestMapping("/picture")
public class PictureController {

    @Autowired
    PictureService pictureService;

    @RequestMapping("/getURL")
    public @ResponseBody
    Results getPicUrl() {
        List<String> urlList = pictureService.getPictureUrl();
        return new Results("获取成功", 1).addObject("pic", urlList);
    }

    @RequestMapping("/addPic")
    public @ResponseBody
    Results insert(Picture picture, @RequestParam("file") MultipartFile file, HttpServletRequest request) throws IOException {
        //判断是否为空
        if (!file.isEmpty()) {
            //获取后缀
            String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
            if (suffix.equals("jgp") || suffix.equals("png")) {
                //编写路径
                String path = request.getSession().getServletContext().getRealPath("") + "Pic"+File.separator + picture.getUserId() + file.getOriginalFilename();
                if (!new File(path).exists()) {
                    new File(path).mkdirs();
                }
                //写入文件
                file.transferTo(new File(path));
                //写入url
                String url = "http://qsq.ngrok.xiaomiqiu.cn/webProjectSSM1_war_exploded/Pic/"+picture.getUserId()+file.getOriginalFilename();
                picture.setUserImg(url);
                if (new File(path).exists()) {
                    //将url写入数据库
                    if (pictureService.addPicture(picture)) {
                        return new Results("接收成功", 1);
                    }
                }
            }
        }
        return new Results("接收失败", 0);
    }
}
